package br.com.furb.service;

import java.util.List;

import br.com.furb.model.Table;
import br.com.furb.service.enums.TableEventType;
import br.com.furb.service.listener.TableObserver;

/**
 * Registra os metadados referente as tabelas.
 *  
 * @since 01/11/2011
 */
public final class Metadata implements TableObserver{
	
	private static Metadata instance;
	
	/**
	 * @return instance
	 */
	public static Metadata getInstance(){
		if(instance == null)
			instance = new Metadata();
		
		return instance;
	}
	
	private TablePersist tablePersist;
	private List<Table> tables;
	
	private Metadata(){
	}
	
	/**
	 * @return tablePersist
	 */
	private TablePersist getTablePersist(){
		if(tablePersist == null){
			tablePersist = TablePersist.getInstance();
			tablePersist.addTableObserver(getInstance());
		}
		
		return tablePersist;
	}
	
	/**
	 * @return tables
	 */
	public List<Table> getTableData(){
		if(tables == null)
			tables = getTablePersist().readAll();
		
		return tables;
	}
	
	/**
	 * @param tableName
	 * @return table
	 */
	public Table getTable(String tableName){
		for(Table table : getTableData())
			if(table.getName().equalsIgnoreCase(tableName))
				return table;
		
		return null;
	}

	/* (non-Javadoc)
	 * @see br.com.furb.service.listener.TableObserver#fireTableChanged(br.com.furb.service.enums.TableEventType, br.com.furb.model.Table)
	 */
	@Override
	public void fireTableChanged(TableEventType eventType, Table table) {
		tables = null;
		System.out.println(eventType);
	}
	
	/**
	 * @return id
	 */
	public Long getMaxTableId(){
		Long max = Long.MIN_VALUE;
		
		for(Table table : getTableData())
			if(table.getCode() > max)
				max = table.getCode();
		
		return max;
	}

}